<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

// 当前激活的标签页
const activeTab = ref('login')

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 游客注册表单数据
const touristForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  name: '',
  email: '',
  phone: ''
})

// 学生注册表单数据已移除

// 表单验证规则
const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 游客注册表单验证规则
const touristRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_: any, value: string, callback: Function) => {
        if (value !== touristForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}



// 表单引用
const loginFormRef = ref<FormInstance>()
const touristFormRef = ref<FormInstance>()

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const success = userStore.login(loginForm.username, loginForm.password)
      if (success) {
        const user = userStore.currentUser
        ElMessage.success(`欢迎回来，${user?.name}`)

        // 根据角色重定向到不同页面
        if (user?.role === 'admin') {
          router.push('/feature-management')
        } else if (user?.role === 'tourist') {
          router.push('/visitor')

        } else {
          router.push('/welcome')
        }
      } else {
        ElMessage.error('用户名或密码错误')
      }
    }
  })
}

// 游客注册处理
const handleTouristRegister = async () => {
  if (!touristFormRef.value) return

  await touristFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const success = userStore.registerTourist({
        username: touristForm.username,
        password: touristForm.password,
        name: touristForm.name,
        email: touristForm.email,
        phone: touristForm.phone
      })

      if (success) {
        ElMessage.success('注册成功，欢迎使用北京旅游系统')
        router.push('/visitor')
      } else {
        ElMessage.error('注册失败，用户名已存在')
      }
    }
  })
}



// 提示信息
const tips = [
  { role: '管理员', username: 'admin', password: 'admin123' },
  { role: '游客', username: 'tourist', password: 'tourist123' }
]
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <div class="logo">
          <svg class="icon" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <path d="M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32zM368 744h-80V280h80v464zm192 0h-80V280h80v464zm192 0h-80V280h80v464z" fill="#c62f2f"/>
          </svg>
        </div>
        <h1>北京旅游系统</h1>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" class="login-tabs">
        <!-- 登录标签页 -->
        <el-tab-pane label="登录" name="login">
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            label-position="top"
          >
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
              >
                <template #prefix>
                  <el-icon><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M288 320a224 224 0 1 0 448 0 224 224 0 1 0-448 0zm544 608H160a32 32 0 0 1-32-32v-96a160 160 0 0 1 160-160h448a160 160 0 0 1 160 160v96a32 32 0 0 1-32 32z"/></svg></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
              >
                <template #prefix>
                  <el-icon><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M224 448a32 32 0 0 0-32 32v384a32 32 0 0 0 32 32h576a32 32 0 0 0 32-32V480a32 32 0 0 0-32-32H224zm0-64h576a96 96 0 0 1 96 96v384a96 96 0 0 1-96 96H224a96 96 0 0 1-96-96V480a96 96 0 0 1 96-96z"/><path fill="currentColor" d="M512 544a32 32 0 0 1 32 32v192a32 32 0 1 1-64 0V576a32 32 0 0 1 32-32zm192-160v-64a192 192 0 1 0-384 0v64h384zM512 64a256 256 0 0 1 256 256v128H256V320A256 256 0 0 1 512 64z"/></svg></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="login-button beijing-button" @click="handleLogin">登录</el-button>
            </el-form-item>
          </el-form>
          <div class="login-tips">
            <p>测试账号：</p>
            <ul>
              <li v-for="(tip, index) in tips" :key="index">
                {{ tip.role }}: {{ tip.username }} / {{ tip.password }}
              </li>
            </ul>
          </div>
        </el-tab-pane>

        <!-- 游客注册标签页 -->
        <el-tab-pane label="游客注册" name="tourist">
          <el-form
            ref="touristFormRef"
            :model="touristForm"
            :rules="touristRules"
            class="register-form"
            label-position="top"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="touristForm.username" placeholder="请设置用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="touristForm.password" type="password" placeholder="请设置密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="touristForm.confirmPassword" type="password" placeholder="请再次输入密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="touristForm.name" placeholder="请输入您的姓名"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="touristForm.email" placeholder="请输入您的邮箱（选填）"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="touristForm.phone" placeholder="请输入您的手机号（选填）"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="success" class="register-button beijing-button" @click="handleTouristRegister">注册</el-button>
            </el-form-item>
          </el-form>
          <div class="register-tips">
            <p>游客用户可以使用以下功能：</p>
            <ul>
              <li>景点信息浏览</li>
              <li>旅游路线规划</li>
              <li>文化遗产保护意识</li>
            </ul>
          </div>
        </el-tab-pane>

        <!-- 学生注册标签页已移除 -->
      </el-tabs>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #c62f2f 0%, #ffcc00 100%);
  background-size: cover;
}

.login-box {
  width: 450px;
  padding: 40px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  max-height: 90vh;
  overflow-y: auto;
}

.login-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 16px;
}

.login-header h1 {
  font-size: 24px;
  color: #c62f2f;
  margin: 0;
  font-weight: 600;
}

.login-tabs {
  width: 100%;
}

.login-form,
.register-form {
  margin-bottom: 20px;
}

.login-button,
.register-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}

.beijing-button {
  background-color: #c62f2f;
  border-color: #c62f2f;
}

.beijing-button:hover {
  background-color: #a52222 !important;
  border-color: #a52222 !important;
}

.login-tips,
.register-tips {
  font-size: 14px;
  color: #606266;
  background-color: #f5f7fa;
  padding: 10px 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.login-tips p,
.register-tips p {
  margin-bottom: 5px;
  font-weight: bold;
}

.login-tips ul,
.register-tips ul {
  padding-left: 20px;
  margin: 0;
}

.icon {
  width: 100%;
  height: 100%;
}

/* 标签页样式 */
:deep(.el-tabs__item) {
  color: #606266;
  font-size: 16px;
}

:deep(.el-tabs__item.is-active) {
  color: #c62f2f;
}

:deep(.el-tabs__active-bar) {
  background-color: #c62f2f;
}
</style>


